﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PearTunes.Model;
using PearTunes.DAL;

namespace PearTunes.WEB.Models
{
    /// <summary>
    /// Class for accessing user entities.
    /// </summary>
    public class UserModel
    {
        /// <summary>
        /// Gets a list of all registered users from the data access layer.
        /// </summary>
        public IList<User> ListUsers()
        {
            return (new PearTunesEntities()).Users.ToList();
        }

        /// <summary>
        /// Forwards information for adding a new user to the data access layer.
        /// </summary>
        /// <param name="username">The name of the user to add</param>
        /// <param name="email">The e-mail address of the user to add</param>
        /// <param name="money">The initial money of the user to add</param>
        /// <param name="password">The password the user provided</param>
        public void AddUser(string username, string email, int money, string password)
        {
            var context = new PearTunesEntities();
            context.Users.Add(new User()
            {
                Name = username,
                Email = email,
                Money = money,
                Password = password,
                BoughtTracks = new List<Track>(),
                UserId = context.GenerateUserId()
            });
            context.SaveChanges();
        }

        /// <summary>
        /// Provides information about the user with the specified username.
        /// </summary>
        /// <param name="username">The name of the user</param>
        /// <returns>A User object</returns>
        public User UserInfo(string username)
        {
            return (new PearTunesEntities()).Users.Where(u => username == u.Name).First();
        }

        /// <summary>
        /// Adds the specified amount of money to the account of the specified user.
        /// </summary>
        /// <param name="username">The name of the user to add money to</param>
        /// <param name="money">The amount of money to add</param>
        public void AddMoney(string username, int money)
        {
            var context = new PearTunesEntities();
            User u = context.Users.Where(us => username == us.Name).First();
            u.Money += money;
            context.SaveChanges();
        }

        /// <summary>
        /// Deletes a user with the specified ID.
        /// </summary>
        /// <param name="userId">The identifier of the user to delete</param>
        public void DeleteUser(int userId)
        {
            PearTunesEntities context = new PearTunesEntities();
            IEnumerable<User> toDelete = context.Users.Where(u => u.UserId == userId);
            if (toDelete.Count() > 0)
                context.Users.Remove(toDelete.First());
            context.SaveChanges();
        }
    }
}